package com.base.util.jniutils;

/**
 * BASE64 工具类
 *
 * @author gj
 */
public class JniBase64 {

    /**
     * Default values for encoder/decoder flags.
     */
    public static final int DEFAULT = 0;

    /**
     * Encoder flag bit to omit the padding '=' characters at the end
     * of the output (if any).
     */
    public static final int NO_PADDING = 1;

    /**
     * Encoder flag bit to omit all line terminators (i.e., the output
     * will be on one long line).
     */
    public static final int NO_WRAP = 2;

    /**
     * Encoder flag bit to indicate lines should be terminated with a
     * CRLF pair instead of just an LF.  Has no effect if {@code
     * NO_WRAP} is specified as well.
     */
    public static final int CRLF = 4;

    /**
     * Encoder/decoder flag bit to indicate using the "URL and
     * filename safe" variant of Base64 (see RFC 3548 section 4) where
     * {@code -} and {@code _} are used in place of {@code +} and
     * {@code /}.
     */
    public static final int URL_SAFE = 8;

    public static byte[] encode(byte[] input, int flags) {
        if (input == null) {
            throw new IllegalArgumentException("bad encode base-64");
        }
        if (input.length == 0) {
            return input;
        }
        byte[] bs = NATIVE_ENCODE(input, input.length, flags);
        if (bs == null) {
            throw new IllegalArgumentException("bad encode base-64");
        }
        return bs;
    }

    public static byte[] decode(byte[] input) {
        if (input == null) {
            throw new IllegalArgumentException("bad encode base-64");
        }
        if (input.length == 0) {
            return input;
        }
        byte[] bs = NATIVE_DECODE(input, input.length);
        if (bs == null) {
            throw new IllegalArgumentException("bad decode base-64");
        }
        return bs;
    }

    public static byte[] decode(String str) {
        return decode(str.getBytes());
    }

    private static native byte[] NATIVE_ENCODE(byte[] input, int inSize, int flags);

    private static native byte[] NATIVE_DECODE(byte[] input, int inSize);
}
